import 'dart:async';
import 'dart:ui';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_goods_recommendation.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/recommend_product_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/views/recommend/product_item.dart';
import 'package:amway_superapp_creator_plugin/widget/flutter_reorderable_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../view_state.dart';

class RecommendProductPage extends StatefulWidget {
  RecommendProductPage({Key key, @required this.ada, @required this.amwayId})
      : super(key: key);

  final ada;
  final amwayId;

  @override
  RecommendProductPageState createState() => new RecommendProductPageState();
}

class RecommendProductPageState extends State<RecommendProductPage> {
  RecommendProductVM viewModel;
  ScrollController _scrollController = ScrollController();

  bool _reorderCallback(Key from, Key to) {
    viewModel.reorderProductList(from, to);
    return true;
  }

  Widget _buildProductList(RecommendProductVM viewModel) {
    return ReorderableList(
      onReorder: _reorderCallback,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onPanDown: (_) {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: CustomScrollView(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                  return RecommendItem(
                    data: viewModel.contentList[index],
                    isFirst: index == 0,
                    isLast: index == viewModel.contentList.length - 1,
                    vm: viewModel,
                    key: ValueKey(viewModel.contentList[index].product.skuCode),
                  );
                },
                childCount: viewModel.contentList.length,
                addAutomaticKeepAlives: true,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOfficialList(RecommendProductVM viewModel,
      [BuildContext context]) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(16),
          ScreenUtil().setHeight(12),
          ScreenUtil().setWidth(16),
          ScreenUtil().setHeight(17)),
      decoration: BoxDecoration(
          color: Colors.white,
          //设置四周圆角 角度
          borderRadius:
          BorderRadius.all(Radius.circular(ScreenUtil().setHeight(12))),
          //设置四周边框
          boxShadow: [
            BoxShadow(
                color: ColorUtil.fromHex('#000000').withOpacity(0.08),
                blurRadius: ScreenUtil().setWidth(12))
          ]),
      child: ListView(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        children: [
          GestureDetector(
              child: _topFolder(),
              onTap: () {
                viewModel.switchRecommendListState();
                WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                  _scrollController.animateTo(
                      _scrollController.position.maxScrollExtent,
                      curve: Curves.easeInOutBack,
                      duration: Duration(milliseconds: 500));
                });
              }),
          viewModel.isFolded
              ? Container(
            width: 0,
            height: 0,
          )
              : ListView(
            shrinkWrap: true,
            padding: EdgeInsets.only(bottom: ScreenUtil().setHeight(13)),
            physics: NeverScrollableScrollPhysics(),
            children: _buildRecommendChildren(viewModel, context),
          )
        ],
      ),
    );
  }

  Widget _topFolder() {
    return Container(
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(16),
          ScreenUtil().setHeight(13), ScreenUtil().setWidth(16), 0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                  child: Text(
                    '官方好物推荐',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: ScreenUtil().setSp(18),
                        color: ColorsConfig.c_2c2c2c),
                  )),
              Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: ScreenUtil().setWidth(6)),
                    child: Text(
                      viewModel.isFolded ? '展开' : '收起',
                      style: TextStyle(
                          color: ColorUtil.fromHex('#000000').withOpacity(0.2),
                          fontSize: ScreenUtil().setSp(14)),
                    ),
                  ),
                  Image.asset(
                      viewModel.isFolded
                          ? 'picture/icon_collapse.png'
                          : 'picture/icon_fold.png',
                      width: ScreenUtil().setWidth(16),
                      height: ScreenUtil().setWidth(16),
                      package: 'amway_superapp_creator_plugin'),
                ],
              )
            ],
          ),
          _buildDivider(viewModel.isFolded)
        ],
      ),
    );
  }

  Widget _buildDivider(bool isFolded) {
    bool allHidden=true;
    viewModel.officialProductList..forEach((element) {
      if(!element.isHidden){
        allHidden=false;
      }
    });

    if (!isFolded&&!allHidden) {
      return Padding(
        padding: EdgeInsets.only(top: ScreenUtil().setSp(13)),
        child:
        Divider(height: ScreenUtil().setHeight(viewModel.isFolded ? 0 : 1)),
      );
    } else {
      return Container(
        height: ScreenUtil().setSp(10),
      );
    }
  }

  List<Widget> _buildRecommendChildren(RecommendProductVM viewModel,
      [BuildContext context]) {
    if (viewModel.isFolded) {
      return [];
    }
    List<HaowuProduct> validList = new List();
    viewModel.officialProductList.forEach((element) {
      if (!element.isHidden) {
        validList.add(element);
      }
    });
    return List<Widget>.generate(
        validList.length,
            (index) => Container(
          height: ScreenUtil().setHeight(147),
          margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(15),
              ScreenUtil().setHeight(15), ScreenUtil().setWidth(15), 0),
          child: _buildOfficialInfo(validList[index], viewModel, context),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<RecommendProductVM>(
        model: RecommendProductVM(api: Provider.of(context)),
        onModelReady: (model) async {
          viewModel = model;
          viewModel.setScrollController(_scrollController);
          viewModel.fetchList(widget.ada, widget.amwayId);
        },
        builder: (context, model, child) => WillPopScope(
              onWillPop: () async {
                if (viewModel.checkAnyItemsEdited()) {
                  showBackDialog(context, model);
                } else {
                  Application.router.pop(context);
                }
                return true;
              },
              child: Scaffold(
                bottomNavigationBar: Container(
                  width: double.infinity,
                  height: ScreenUtil().setHeight(92),
                  decoration: new BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          color: ColorUtil.fromHex('#26000000'),
                          offset: Offset(0, -ScreenUtil().setHeight(2)),
                          blurRadius: ScreenUtil().setHeight(15))
                    ],
                  ),
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil().setWidth(16),
                        ScreenUtil().setHeight(16),
                        ScreenUtil().setWidth(16),
                        ScreenUtil().setHeight(34)),
                    child: FlatButton(
                      onPressed: () {
                        model.modifyList(_scrollController, (data) {
                          ToastUtils.showShortToast('保存成功');
                          Application.router.pop(context, 'success');
                        });
                      },
                      color: ColorUtil.fromHex('#FF396E75'),
                      child: Center(
                        child: new Text('保存并提交',
                            style: TextStyle(color: Colors.white)),
                      ),
                      shape: StadiumBorder(),
                    ),
                  ),
                ),
                appBar: AppBar(
                  backgroundColor: Colors.white,
                  elevation: 0,
                  //去除阴影
                  brightness: Brightness.light,
                  //黑色状态栏
                  title: Text(
                    '好物推荐',
                    style: TextStyle(
                        fontSize: ScreenUtil().setWidth(20),
                        color: Colors.black),
                  ),
                  centerTitle: true,
                  leading: GestureDetector(
                    child: BaseView.buildBackButton(),
                    onTap: () {
                      if (viewModel.checkAnyItemsEdited()) {
                        showBackDialog(context, viewModel);
                      } else {
                        Application.router.pop(context);
                      }
                    },
                  ),
                ),
                body: Stack(
                  alignment: Alignment.center,
                  children: [
                    Container(
                      color: Colors.white,
                      height: double.maxFinite,
                      child: ListView(
                        controller: _scrollController,
                        padding:
                            EdgeInsets.only(bottom: ScreenUtil().setHeight(92)),
                        children: [
                          GestureDetector(
                            child: Container(
                                child: Opacity(
                                  opacity: model.contentList.length>=50?0.3:1,
                                  child: Image.asset(
                                      'picture/icon_choose_custom_product.png',
                                      fit: BoxFit.fill,
                                      color: model.contentList.length>=50?Colors.grey:Colors.transparent,
                                      colorBlendMode: BlendMode.hue,
                                      package: 'amway_superapp_creator_plugin'),
                                ),
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil().setWidth(16),
                                    ScreenUtil().setWidth(16),
                                    ScreenUtil().setWidth(16),
                                    0),
                                height: ScreenUtil().setWidth(120)),
                            onTap: () {
                              Map<String, dynamic> map = Map();
                              List<HaowuProduct> productList = [];
                              model.contentList.forEach((element) {
                                productList.add(element.product);
                              });
                              //已经在好物列表里面的商品，传递过去用于更新选中状态
                              if (productList.isNotEmpty) {
                                map['items'] = productList;
                                if(productList.length>=50){
                                  ToastUtils.showShortToast('无法添加');
                                  return;
                                }
                              }
                              Application.router
                                  .navigateTo(context, Routes.shopCategory,
                                      routeSettings:
                                          RouteSettings(arguments: map))
                                  .then((value) {
                                if (value == null) {
                                  return;
                                }
                                model.addCustom(value);
                                // provide.setShop(value);
                              });
                            },
                          ),
                          Padding(
                              padding: EdgeInsets.fromLTRB(
                                  ScreenUtil().setWidth(16),
                                  ScreenUtil().setHeight(10),
                                  0,
                                  ScreenUtil().setHeight(20)),
                              child: Text(
                                '以下商品可以通过长按拖拽方式调整展示顺序',
                                style: TextStyle(
                                    fontSize: ScreenUtil().setWidth(12),
                                    color: ColorsConfig.colorBlack
                                        .withOpacity(0.3)),
                              )),
                          _buildProductList(model),
                          _buildOfficialList(model, context)
                        ],
                        shrinkWrap: true,
                      ),
                    ),
                    model.state == ViewState.Busy
                        ? Container(
                            width: double.maxFinite,
                            height: double.maxFinite,
                            child: Center(
                                child: LoadingDialog(
                                    canceledOnTouchOutside: false,
                                    tipMsg:
                                        viewModel.isLoading ? "正在保存" : "加载中")))
                        : Center(
                            child: Container(
                              width: 0,
                              height: 0,
                            ),
                          ),
                  ],
                ),
              ),
            ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(RecommendProductPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }
}

///如果是isFromTop,显示垃圾桶按钮，如果否，显示添加按钮
Widget _buildOfficialInfo(
    HaowuProduct product, RecommendProductVM viewModel, BuildContext context) {
  String widgetPath = 'picture/icon_add_product.png';
  Widget _rightButton = GestureDetector(
    child: Padding(
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(110)),
      child: Opacity(
        opacity: viewModel.contentList.length>=50?0.3:1,
        child: Image.asset(widgetPath,
            width: ScreenUtil().setWidth(24),
            height: ScreenUtil().setWidth(24),
            package: 'amway_superapp_creator_plugin'),
      ),
    ),
    onTap: () {
      ZhugeGoodsRecommendationAnalysis.goodsReCommendaionAddGoods("好物推荐页面");
      viewModel.addOfficial(product);
    },
  );

  String _buildTagText(List<String> tagList) {
    StringBuffer buffer = StringBuffer();
    if (tagList != null && tagList.isNotEmpty) {
      for (int i = 0; i < tagList.length; i++) {
        if (i != tagList.length - 1) {
          buffer.write(tagList.elementAt(i) + '|');
        } else {
          buffer.write(tagList.elementAt(i));
        }
      }
    }
    // if(buffer.isEmpty){
    //   buffer.write('空标|空标|空标');
    // }
    return buffer.toString();
  }

  if (product.isHidden) {
    return Container(width: 0, height: 0);
  }

  return Row(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: [
      Expanded(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.network(
                product.picture != null
                    ? product.picture
                    : 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603966641602&di=59dc495e8c57f2da98719f80d1d816c2&imgtype=0&src=http%3A%2F%2Fpic6.58cdn.com.cn%2Fmobile%2Fbig%2Fn_v242f9dea1883642f49bf07935db6d95ca.jpg%3Fw%3D425%26h%3D320',
                width: ScreenUtil().setWidth(105),
                height: ScreenUtil().setWidth(105)),
            Expanded(
                child: Container(
                  padding: EdgeInsets.only(left: ScreenUtil().setWidth(12)),
                  height: ScreenUtil().setHeight(200),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(product.productName != null ? product.productName : '安利',
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(18),
                              fontWeight: FontWeight.bold,
                              color: ColorsConfig.c_2c2c2c,
                              height: 1.4)),
                      Container(
                        width: ScreenUtil().setWidth(194),
                        child: Text(_buildTagText(product.tagList),
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(12),
                                color: ColorsConfig.c_396E75,
                                height: 1.66)),
                      ),
                      DefaultTextStyle(
                        style: TextStyle(
                            color: ColorUtil.fromHex('#CD0000'),
                            fontWeight: FontWeight.bold),
                        child: Padding(
                          padding: EdgeInsets.only(top: ScreenUtil().setHeight(8)),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Text(
                                  product.priceData != null &&
                                      product.priceData.currency == "RMB"
                                      ? "¥"
                                      : '¥',
                                  style:
                                  TextStyle(fontSize: ScreenUtil().setSp(12))),
                              Text(
                                product.priceData != null
                                    ? product.priceData.price.toStringAsFixed(2)
                                    : '66.66',
                                style: TextStyle(fontSize: ScreenUtil().setSp(16)),
                              )
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                )),
            _rightButton
          ],
        ),
      )
    ],
  );
}

void showBackDialog(BuildContext context, RecommendProductVM model) {
  showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) {
        return CommTipDialog(
          content: '返回上一步会丢失当前已编辑信息，是否确认返回？',
          confirmText: "确认",
          closeText: '取消',
          confirmCallback: () {
            Application.router.pop(context);
          },
        );
      });
}
